import {
  Form,
  Input,
  Table,
  Button,
  Modal,
  Space,
  message,
  Popconfirm,
  Select,
} from "antd";
import { useState, useEffect } from "react";
import type { ColumnsType } from "antd/es/table";
import http from "../../../utils/http";
import { CSVLink } from "react-csv";

import "./index.scss";

const UserManage = () => {
  //表内容
  const [data, setData] = useState([]);
  const columns: ColumnsType<DataType> = [
    {
      title: "账号",
      dataIndex: "username",
      key: "username",
    },
    {
      title: "密码",
      dataIndex: "password",
      key: "password",
    },
    {
      title: "姓名",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "电话",
      dataIndex: "phone",
      key: "phone",
    },
    {
      title: "身份",
      dataIndex: "identity",
      key: "identity",
    },
    {
      title: "操作",
      key: "action",
      render: (_: any, record: any) => (
        <Space size="middle">
          <a
            onClick={() => {
              showEdit(record);
            }}
            className="edit"
          >
            编辑
          </a>
          <Popconfirm
            title="你确定删除这条信息吗?"
            onConfirm={() => {
              confirm(record);
            }}
            onCancel={cancel}
            okText="确定"
            cancelText="取消"
          >
            <a href="#" className="del">
              删除
            </a>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 表格信息
  interface DataType {
    key: string;
    username: String;
    password: String;
    state: String;
  }

  //渲染数据
  const getData = () => {
    http({
      url: "/getUser",
    }).then((res) => {
      console.log("所有数据", res);
      let _data = res.data.map((v: { id: number }) => {
        return { ...v, key: v.id };
      });
      setData(_data);
    });
  };
  useEffect(() => {
    getData();
  }, []);

  // 编辑框
  const [editForm] = Form.useForm();
  const [isModalOpen, setIsEditOpen] = useState(false);

  const showEdit = (record: any) => {
    console.log("editrecord", record);
    editForm.setFieldsValue({ ...record });
    setIsEditOpen(true);
  };
  // 确定编辑
  const handleOk = () => {
    const data = editForm.getFieldsValue(true);
    http({
      url: "/editUser",
      method: "post",
      data: data,
    }).then((res: { [key: string]: any }) => {
      console.log(res);
      if (res.error == 0) {
        message.success("修改成功");
        setIsEditOpen(false);
        getData();
      } else {
        message.error("修改失败");
      }
    });
    setIsEditOpen(false);
  };
  const handleCancel = () => {
    setIsEditOpen(false);
  };

  // 确定删除
  const confirm = (record: { id: number }) => {
    http({
      url: "/delUser",
      method: "post",
      data: {
        id: record.id,
      },
    }).then((res: { [key: string]: any }) => {
      if (res.error == 0) {
        message.success("删除成功");
        getData();
      } else {
        message.error("删除失败");
      }
    });
  };
  const cancel = () => {
    message.error("取消删除");
  };

  //导出excel表
  const toExcel = () => {
    console.log("all", data);
  };

  // 新增
  const [isAddOpen, setIsAddOpen] = useState(false);
  const showAdd = () => {
    setIsAddOpen(true);
  };
  // 确定新增
  const [addText] = Form.useForm();
  const onAdd = (values: any) => {
    console.log("Add:", values);
    http({
      url: "/addUser",
      method: "post",
      data: {
        username: values.username,
        password: values.password,
        name: values.name,
        phone: values.phone,
        identity: values.identity,
      },
    }).then((res: { [key: string]: any }) => {
      console.log(res);
      if (res.error == 0) {
        message.success("添加成功");
        setIsAddOpen(false);
        addText.resetFields();
        getData();
      } else {
        message.error("添加失败");
      }
    });
  };
  const handleCancelAdd = () => {
    setIsAddOpen(false);
  };

  return (
    <div className="userManage">
      <div className="title">账号管理</div>
      <div className="hr"></div>

      <Form
        name="basic"
        initialValues={{ remember: true }}
        autoComplete="off"
        className="form"
      >
        <Form.Item>
          <Button onClick={toExcel}>
            <CSVLink data={data} className="edit" filename="账号导出表.csv">
              导出结果
            </CSVLink>
          </Button>
        </Form.Item>

        <Form.Item>
          <Button className="btn" onClick={showAdd}>
            新增
          </Button>
        </Form.Item>
      </Form>

      <Table
        columns={columns}
        dataSource={data}
        bordered={true}
        pagination={{ defaultPageSize: 5 }}
      />

      {/* 编辑框 */}
      <Modal
        title="编辑"
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
        okText={"确认"}
        cancelText={"取消"}
      >
        <Form
          form={editForm}
          name="basic"
          initialValues={{ remember: true }}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 16 }}
          autoComplete="off"
        >
          <Form.Item
            label="账号"
            name="username"
            rules={[
              {
                required: true,
                message: "请输入你的账号!",
              },
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="密码"
            rules={[{ required: true, message: "请输入你的密码!" }]}
            name="password"
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="姓名"
            name="name"
            rules={[
              {
                required: true,
                pattern: /^[\u2E80-\u9FFF]+$/,
                message: "请输入你的姓名!",
              },
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="联系电话"
            rules={[
              {
                required: true,
                pattern: /^1[3456789]\d{9}$/,
                message: "请输入正确的联系电话!",
              },
            ]}
            name="phone"
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="身份"
            rules={[{ required: true, message: "请选择你的身份!" }]}
            name="identity"
          >
            <Select>
              <Select.Option value="教育局">教育局</Select.Option>
              <Select.Option value="中心校">中心校</Select.Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>

      {/* 新增框 */}
      <Modal
        title="新增"
        open={isAddOpen}
        onCancel={handleCancelAdd}
        footer={null}
      >
        <Form
          form={addText}
          name="basic"
          initialValues={{ remember: true }}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 16 }}
          autoComplete="off"
          onFinish={onAdd}
        >
          <div className="items">
            <Form.Item
              label="账号"
              name="username"
              rules={[
                {
                  required: true,
                  message: "请输入你的账号!",
                },
              ]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              label="密码"
              rules={[{ required: true, message: "请输入你的密码!" }]}
              name="password"
            >
              <Input />
            </Form.Item>

            <Form.Item
              label="姓名"
              name="name"
              rules={[
                {
                  required: true,
                  pattern: /^[\u2E80-\u9FFF]+$/,
                  message: "请输入你的姓名!",
                },
              ]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              label="联系电话"
              rules={[
                {
                  required: true,
                  pattern: /^1[3456789]\d{9}$/,
                  message: "请输入正确的联系电话!",
                },
              ]}
              name="phone"
            >
              <Input />
            </Form.Item>

            <Form.Item
              label="身份"
              rules={[{ required: true, message: "请选择你的身份!" }]}
              name="identity"
            >
              <Select>
                <Select.Option value="教育局">教育局</Select.Option>
                <Select.Option value="中心校">中心校</Select.Option>
              </Select>
            </Form.Item>
          </div>

          <Form.Item wrapperCol={{ offset: 16, span: 16 }}>
            <Button
              className="clear"
              htmlType="button"
              onClick={handleCancelAdd}
            >
              取消
            </Button>
            <Button type="primary" htmlType="submit">
              确定
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default UserManage;
